using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AppAPIUtils;
using AppTableUtils;
using Newtonsoft.Json;
using MyUnityUtils;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using UnityEngine.Serialization;
using UnityEngine.UI;
using Text = UnityEngine.UI.Text;
using DG.Tweening;


namespace EmailPanel
{
    
    public class EmailFileData : BdUtils.IJson
    {
        public List<int> read_id_ls { get; set; }
    }
    
    public class TestTable : MonoBehaviour
    {
        public GameObject scroll_content_parent_obj;
        public Text detail_title;
        public Text detail_sender;
        public Text detail_time;
        public Text detail_content;
        // public Text detail_attachment;
        public GameObject detail_attachment_parent_obj;

        // private int current_email_index = -1;
        public GameObject email_prefab_obj;

        private int current_email_index 
        {
            get { return detail_ctrl.current_email_index; }
            set { detail_ctrl.current_email_index = value; }
        }
        
        private DetailCtrl detail_ctrl;
        
        private void Awake()
        {
            detail_ctrl = scroll_content_parent_obj.transform.GetComponentInParent<DetailCtrl>();
            BdPackage.BdUtils.assert(detail_ctrl != null);

            BaseUtils.clear_children(scroll_content_parent_obj);
            BaseUtils.clear_children(detail_attachment_parent_obj);
        }

        // Start is called before the first frame update
        void Start()
        {
            MyListView.MyListResponse response;
            try
            {
                response = APIUtils.request_list_view("/api/index/Email/");
            }
            catch (Exception e)
            {
                BdPackage.BdTools.show_message_box("Network Error!", "获取邮件信息失败!");
                throw;
            }
            // BdPackage.BdUtils.log(response.status, response.msg, response.result);
            // BdPackage.BdUtils.log("data --- ", response.result.data);
            var dc_ls = response.result.data;

            if (dc_ls.Count > 0)
                current_email_index = 0;
            
            string t_now = BdPackage.BdUtils.TimeUtils.get_time_string();
            
            // BdPackage.BdUtils.log($" --- t_now: {t_now}");
            // var email_dt = JsonDataTableConverter.ListToDataTable(dc_ls);
            // // TableUtils.show_data_table(email_dt);
            // // var info_i = BdUtils.conv_dc_to_cls_instance<EmailInfo>(TableUtils.conv_row_to_dc(email_dt.Rows[0]));
            // var _fu_jian_dc_ls = email_dt.Rows[0]["fu_jian_dc_ls"];
            // string json = JsonConvert.SerializeObject(_fu_jian_dc_ls);
            // var fu_jian_dc_ls = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
            // BdPackage.BdUtils.log("--- fu_jian_dc_ls:", fu_jian_dc_ls);
            // TableUtils.show_one_row();
            
            for (var i = 0; i < dc_ls.Count; i++)
            {
                var dc_i = dc_ls[i]; 
                GameObject email_obj_i = UnityEngine.Object.Instantiate(email_prefab_obj, Vector3.zero, Quaternion.identity, parent: scroll_content_parent_obj.transform);
                var email_info_i = BdUtils.conv_dc_to_cls_instance<EmailInfo>(dc_i);

                if (detail_ctrl.email_file_data.read_id_ls.Contains(email_info_i.id))
                {
                    var is_new = email_obj_i.transform.Find("IsNew").gameObject;
                    is_new.SetActive(false);
                }

                string guo_qi_shi_jian = email_info_i.guo_qi_shi_jian;
                var seconds = UnityTimeUtils.CalculateTimeDifference(t_now, guo_qi_shi_jian).TotalSeconds;
                
                string duration_string;
                if (seconds > 0)
                {
                    string formatted_duration = UnityTimeUtils.FormatDuration(BdPackage.BdUtils.conv_to_int(seconds));
                    duration_string = $"[{formatted_duration}]后过期";
                }
                else
                {
                    string formatted_duration = UnityTimeUtils.FormatDuration(BdPackage.BdUtils.conv_to_int(-seconds));
                    duration_string = $"已过期[{formatted_duration}]";
                }
                email_obj_i.transform.Find("Title").GetComponent<Text>().text = email_info_i.biao_ti;
                email_obj_i.transform.Find("Sender/number_text").GetComponent<Text>().text = email_info_i.fa_jian_ren;
                email_obj_i.transform.Find("ExpirationTime").GetComponent<Text>().text = duration_string;

                BdPackage.BdUtils.assert(email_info_i.fu_jian_dc_ls.Count > 0, "附件不能为空!");
                if (email_info_i.fu_jian_dc_ls.Count > 0)
                {
                    int last_id = email_info_i.fu_jian_dc_ls.Count - 1;
                    var item_dc_i = email_info_i.fu_jian_dc_ls[last_id];
                    var item_id = item_dc_i["id"];
                    
                    var row_i = AppTableUtils.TableUtils.get(detail_ctrl.item_info_dt, item_id);
                    string item_prefab_name = BdPackage.BdUtils.conv_to_string(row_i["预制体"]);

                    string tem_prefab_dir_path = "Prefabs/icons";
                    GameObject item_obj = ObjectPool.instance.GetObj(item_prefab_name, tem_prefab_dir_path);

                    var image_i = email_obj_i.transform.Find("Icon/Image").GetComponent<Image>();
                    image_i.sprite = item_obj.transform.Find("Icon").GetComponent<Image>().sprite;
                    
                    // int item_num = item_dc_i["num"];
                    // item_obj.transform.Find("Number/Text").GetComponent<Text>().text = $"{item_num}";

                }
                
                email_obj_i.name = $"Email_{email_info_i.id}";
                email_obj_i.GetComponent<EmailBtn>().obj_id = email_info_i.id;
                
                detail_ctrl.email_info_dc.Add(email_info_i.id, email_info_i);
                
                if (i == 0)
                {
                    float t = 0.025f;  // [延迟/等待/休眠/timeout]t秒后执行
                    DOTween.To(() => t, (x) => t = x, 0, t).OnComplete(
                        () =>
                        {
                            var btn = email_obj_i.GetComponent<Button>();
                            btn.onClick.Invoke();
                        }
                        );
                }
            }
        }
            
        public class MyBaseResponse : BdUtils.IJson
        {
            public int status { get; set; }

            public string msg { get; set; }

            public List<Dictionary<string, object>> result { get; set; }
        }
    }
    
    public class EmailInfo : BdUtils.IJson
    {
        public int id { get; set; }
        public string biao_ti { get; set; }
        public string fa_jian_ren { get; set; }
        public string nei_rong { get; set; }
        public string guo_qi_shi_jian { get; set; }
        public string fa_song_shi_jian { get; set; }
            
        public List<Dictionary<string, int>> fu_jian_dc_ls { get; set; }
            
    }
}